﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.UI;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;
using WebApi.Areas.Service.Models;

namespace WebApi.Areas.Service.Controllers
{
    public class SfoodController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage Search()
        {
            //var client = new MongoClient("mongodb://atsoftware.vn:27017");
            //var server = client.GetServer();
            //var database = server.GetDatabase("sfood");
            //var sfood = database.GetCollection<SfoodModel>("Sfood");
            //var clientCity = database.GetCollection<City>("client_city");
            //var clientDistrict = database.GetCollection<District>("client_district");
            //var server_food = database.GetCollection<Food>("server_Food");
            //var server_category = database.GetCollection<Category>("server_Category");
            //var category = database.GetCollection<CategoryModel>("Category");

            ////add tinh
            //var data = sfood.FindAll().Select(x => new { x.Id, x.city, x.district, x.address, x.name, x.food_id });
            //foreach (var item in data)
            //{
            //    string keyCity = ConvertToUnSign(item.city).ToLower();

            //    var queryOne = Query<City>.Where(x => x.key == keyCity);
            //    var dataCity = clientCity.FindOne(queryOne);
            //    if (dataCity == null)
            //    {
            //        var row = new City
            //        {
            //            key = keyCity,
            //            name = item.city,
            //            point = 0,
            //            modDate = FomatEpochTime(DateTime.Now),
            //            status = 0
            //        };
            //        clientCity.Insert(row);
            //    }
            //}


            ////add huyen
            //var listCity = clientCity.FindAll().Select(x => new { x.Id, x.key, x.name });//list tinh
            //foreach (var item in listCity)
            //{
            //    var queryTinh = Query<SfoodModel>.Where(x => x.city == item.name);
            //    var dataTinh = sfood.Find(queryTinh).Select(x => new { x.Id, x.city, x.district, x.address, x.name, x.food_id });
            //    foreach (var i in dataTinh)
            //    {
            //        string keyDistrict = ConvertToUnSign(i.district).ToLower();

            //        var queryOne = Query<District>.Where(x => x.key == keyDistrict && x.city_id == item.Id);
            //        var datadictric = clientDistrict.FindOne(queryOne);

            //        if (datadictric == null)
            //        {
            //            var row = new District
            //            {
            //                city_id = item.Id,
            //                key = keyDistrict,
            //                name = i.district,
            //                point = 0,
            //                modDate = FomatEpochTime(DateTime.Now),
            //                status = 0
            //            };
            //            clientDistrict.Insert(row);
            //        }
            //    }
            //}

            ////tao bang food rieng
            //var data = sfood.FindAll();
            //foreach (var item in data)
            //{
            //    var cityfirt = clientCity.FindOne(Query<City>.Where(x => x.name == item.city));
            //    if (cityfirt != null)
            //    {
            //        var district = clientDistrict.FindOne(Query<District>.Where(x => x.city_id == cityfirt.Id && x.name == item.district));
            //        if (district != null)
            //        {
            //            var categorydata = server_category.FindOne(Query<Category>.Where(x => x.cate_id == item.category_id));
            //            if (categorydata != null)
            //            {
            //                var gia = new Price
            //                {
            //                    max = Int64.Parse(Regex.Replace(item.price.max, ",", "")),
            //                    min = Int64.Parse(Regex.Replace(item.price.min, ",", ""))
            //                };
            //                string key = ConvertToUnSign(item.name) + " " + ConvertToUnSign(item.address);
            //                key = key.ToLower();
            //                var row = new Food
            //                {
            //                    address = item.address,
            //                    avg_rating = item.avg_rating,
            //                    category_id = categorydata.Id,
            //                    city = cityfirt.Id,
            //                    desc = item.desc,
            //                    district = district.Id,
            //                    facilities = item.facilities,
            //                    infos = item.infos,
            //                    key = key,
            //                    location = item.location,
            //                    name = item.name,
            //                    phone = item.phone,
            //                    picture_path = item.picture_path,
            //                    price = gia,
            //                    pros = item.pros,
            //                    status = item.status,
            //                    total_checkins = item.total_checkins,
            //                    total_favourite = item.total_favourite,
            //                    total_review = item.total_review,
            //                    total_view = item.total_view,
            //                    website = item.website
            //                };
            //                server_food.Insert(row);
            //            }
            //        }
            //    }
            //}

            ////add category
            //var data = category.FindAll();
            //foreach (var item in data)
            //{

            //    string key = ConvertToUnSign(item.name);
            //    key = key.ToLower();
            //    var row = new Category
            //    {
            //        cate_id = item.cate_id,
            //        key = key,
            //        name = item.name,
            //        status = item.status
            //    };
            //    server_category.Insert(row);

            //}
            return Request.CreateResponse(HttpStatusCode.OK, "ok");

        }

        [HttpGet]
        public HttpResponseMessage City([FromUri]InputUpdateModel model)
        {
            var data = new ReturnData<List<City>>();
            if (ModelState.IsValid && model != null)
            {
                var client = new MongoClient("mongodb://atsoftware.vn:27017");
                var server = client.GetServer();
                var database = server.GetDatabase("sfood");
                var clientCity = database.GetCollection<City>("client_city");
                if (model.date == 0)
                {
                    data.data = clientCity.FindAll().ToList();
                }
                else
                {
                    var query = Query<City>.Where(x => x.modDate > model.date);
                    data.data = clientCity.Find(query).ToList();
                }
                data.success = true;
                return Request.CreateResponse(HttpStatusCode.OK, data);
            }
            data.success = false;
            data.error = "Tham số không đúng định dạng";
            return Request.CreateResponse(HttpStatusCode.OK, data);

        }

        [HttpGet]
        public HttpResponseMessage Category([FromUri]InputUpdateModel model)
        {
            var data = new ReturnData<List<Category>>();
            if (ModelState.IsValid && model != null)
            {
                var client = new MongoClient("mongodb://atsoftware.vn:27017");
                var server = client.GetServer();
                var database = server.GetDatabase("sfood");
                var clientCategory = database.GetCollection<Category>("client_category");
                if (model.date == 0)
                {
                    data.data = clientCategory.FindAll().ToList();
                }
                else
                {
                    var query = Query<City>.Where(x => x.modDate > model.date);
                    data.data = clientCategory.Find(query).ToList();
                }
                data.success = true;
                return Request.CreateResponse(HttpStatusCode.OK, data);
            }
            data.success = false;
            data.error = "Tham số không đúng định dạng";
            return Request.CreateResponse(HttpStatusCode.OK, data);

        }

        [HttpGet]
        public HttpResponseMessage District([FromUri]InputUpdateModel model)
        {
            var data = new ReturnData<List<District>>();
            if (ModelState.IsValid && model != null)
            {
                var client = new MongoClient("mongodb://atsoftware.vn:27017");
                var server = client.GetServer();
                var database = server.GetDatabase("sfood");
                var clientDistrict = database.GetCollection<District>("client_district");

                if (model.date == 0)
                {
                    data.data = clientDistrict.FindAll().ToList();
                }
                else
                {
                    var query = Query<City>.Where(x => x.modDate > model.date);
                    data.data = clientDistrict.Find(query).ToList();
                }
                data.success = true;
                return Request.CreateResponse(HttpStatusCode.OK, data);
            }
            data.success = false;
            data.error = "Tham số không đúng định dạng";
            return Request.CreateResponse(HttpStatusCode.OK, data);
        }

        [HttpGet]
        public HttpResponseMessage SuggestFood([FromUri]InputSuggestModel model)
        {
            string search = ConvertToUnSign(model.food).ToLower();
            var data = new ReturnData<List<string>>();
            if (ModelState.IsValid && model != null)
            {
                var client = new MongoClient("mongodb://atsoftware.vn:27017");
                var server = client.GetServer();
                var database = server.GetDatabase("sfood");
                var clientFoods = database.GetCollection<Food>("server_food");

                IMongoQuery query;

                if (!string.IsNullOrEmpty(model.district))
                {
                    // co quan huyen
                    query = Query.And(Query.EQ("city", model.city), Query.EQ("district", model.district), Query.Matches("key", search));                    
                }
                else
                {
                    //search theo ten thoi
                    query = Query.And(Query.EQ("city", model.city), Query.Matches("key", search));
                }
                data.data = clientFoods.Find(query).Select(x => x.name + " " + x.address).Take(10).ToList();
                data.success = true;
                return Request.CreateResponse(HttpStatusCode.OK, data);
            }
            data.success = false;
            data.error = "Tham số không đúng định dạng";
            return Request.CreateResponse(HttpStatusCode.OK, data);
        }

        [HttpGet]
        public HttpResponseMessage SearchFood([FromUri]InputSearchModel model)
        {
            string search = ConvertToUnSign(model.food).ToLower();
            var data = new ReturnPageData<List<Food>>();
            if (ModelState.IsValid && model != null)
            {
                var client = new MongoClient("mongodb://atsoftware.vn:27017");
                var server = client.GetServer();
                var database = server.GetDatabase("sfood");
                var clientFoods = database.GetCollection<Food>("server_food");

                IMongoQuery query;

                if (!string.IsNullOrEmpty(model.district) || !string.IsNullOrEmpty(model.category))//co quan hoac co danh muc
                {
                    if (!string.IsNullOrEmpty(model.district) && string.IsNullOrEmpty(model.category))
                    {
                        // co quan huyen
                        query = Query.And(Query.EQ("city", model.city), Query.EQ("district", model.district), Query.Matches("key", search));    
                    }
                    else if (string.IsNullOrEmpty(model.district) && !string.IsNullOrEmpty(model.category))
                    {
                        // co danh muc
                        query = Query.And(Query.EQ("city", model.city), Query.EQ("category", model.category), Query.Matches("key", search));    
                    }
                    else
                    {
                        //co ca 2
                        query = Query.And(Query.EQ("city", model.city), Query.EQ("category", model.category), Query.EQ("district", model.district), Query.Matches("key", search));    
                    }
                    
                }
                else
                {
                    //search theo ten thoi
                    query = Query.And(Query.EQ("city", model.city), Query.Matches("key", search));
                }
                data.paging = new Paging 
                { 
                    page = model.page ,
                    total = clientFoods.Count(),
                    pagesize = model.pagesize
                };

                int skip = model.pagesize;
                if (data.paging.total > model.total && model.total != 0)
                {
                    skip =(int) (skip - (data.paging.total - model.total));
                }
                data.data = clientFoods.Find(query).OrderBy(x=>x.Id).Skip(skip).Take(model.pagesize).ToList();
                data.success = true;
                return Request.CreateResponse(HttpStatusCode.OK, data);
            }
            data.success = false;
            data.error = "Tham số không đúng định dạng";
            return Request.CreateResponse(HttpStatusCode.OK, data);
        }

        public static string ConvertToUnSign(string s)
        {
            Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string temp = s.Normalize(NormalizationForm.FormD);
            return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }

        public static Int64 FomatEpochTime(DateTime? date)
        {
            DateTime datelocal = DateTime.Now;
            if (date != null)
            {
                datelocal = (DateTime)date;
            }
            return (Int64)(datelocal.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
        }

        public static DateTime FomatLocalTime(Int64 epochTime)
        {
            return new DateTime(1970, 1, 1).AddSeconds(epochTime).ToLocalTime();
        }
    }
}
